package org.sword.wechat4j.util;

import java.io.UnsupportedEncodingException;

import org.apache.log4j.Logger;
import org.sword.lang.HttpUtils;
import org.sword.wechat4j.token.RqSceneTicket;
import org.sword.wechat4j.token.TokenProxy;

import com.alibaba.fastjson.JSONObject;

/**   
* @Title: QrSceneUtil.java 
* @Package com.viewhigh.healthwx.util 
* @Description: 带参数二维码工具类
* @author liusongqing 
* @Company www.viewhigh.com
* @date 2016年4月29日 下午1:58:49 
* @version V1.0   
*/
public class QrSceneUtil {
    private static Logger logger = Logger.getLogger(QrSceneUtil.class);
    
    private String accessToken;   
    public QrSceneUtil(){
        this.accessToken = TokenProxy.accessToken();
    }
    /**临时二维码
     * http请求方式: POST
       URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
       POST数据格式：json
       POST数据例子：{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
     */
    private static final String GET_TEMP_TICKET_URL= "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    /**永久二维码
     * http请求方式: POST
        URL: https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN
        POST数据格式：json
        POST数据例子：{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": 123}}}
                        或者也可以使用以下POST数据创建字符串形式的二维码参数：
        {"action_name": "QR_LIMIT_STR_SCENE", "action_info": {"scene": {"scene_str": "123"}}}
     */
    private static final String GET_LIMIT_TICKET_URL= "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=";
    /**
     * 获取二维码
     */
    private static final String GET_QRCODE_URL= "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=";
  
    public static void main(String[] args) {
      /*  QrSceneUtil qr = new QrSceneUtil();
        Ticket t = qr.createTempTicket("1111");
        String qrurl = qr.getQrcodeUrl(t.getTicket());
        System.out.println(qrurl);*/
    }
    /**
     * 
    * @Title: createTempTicket 
    * @Description: 获取临时二维码 
    * @param @param sceneId 整型参数
    * @param @return    设定文件 
    * @return Ticket    返回类型 
    * @throws
     */
    public RqSceneTicket createTempTicket(String sceneId){
        RqSceneTicket ticket = new RqSceneTicket();
        //构造请求数据
        String url = GET_TEMP_TICKET_URL + this.accessToken;
        JSONObject json = new JSONObject();
        json.put("expire_seconds", "2592000");
        json.put("action_name", "QR_SCENE");
        JSONObject scene = new JSONObject();
        JSONObject actionInfo = new JSONObject();       
        scene.put("scene_id", sceneId);       
        actionInfo.put("scene", scene);
        json.put("action_info", actionInfo);
        String data = json.toJSONString();
        
        String result = HttpUtils.post(url, data);
        logger.info("post result:" + result);
        //解析请求数据
        JSONObject resultJson = JSONObject.parseObject(result);
        if(null != resultJson){
            ticket.setExpire_seconds("expire_seconds");
            ticket.setTicket(resultJson.getString("ticket"));
            ticket.setUrl(resultJson.getString("url "));
        }else{
            logger.error("get template id error");
        }
        return ticket;
    }
    /**
     * 
    * @Title: createLimitTicket 
    * @Description: 获取永久二维码
    * @param @param scene_str 二维码字符串Key
    * @param @return    设定文件 
    * @return Ticket    返回类型 
    * @throws
     */
    public RqSceneTicket createLimitTicket(String scene_str){
        RqSceneTicket ticket = new RqSceneTicket();
        //构造请求数据
        String url = GET_LIMIT_TICKET_URL + this.accessToken;
        JSONObject json = new JSONObject();
        json.put("action_name", "QR_LIMIT_SCENE");
        JSONObject scene = new JSONObject();
        JSONObject actionInfo = new JSONObject();       
        scene.put("scene_str", scene_str);       
        actionInfo.put("scene", scene);
        json.put("action_info", actionInfo);
        String data = json.toJSONString();
        
        String result = HttpUtils.post(url, data);
        logger.info("post result:" + result);
        //解析请求数据
        JSONObject resultJson = JSONObject.parseObject(result);
        if(resultJson.getString("errcode").equals("40013")){
            logger.error("get template id error:" + resultJson.getString("errmsg"));
        }else{
            ticket.setTicket(resultJson.getString("ticket"));
            ticket.setUrl(resultJson.getString("url "));
        }
        return ticket;
    }
    /**
     * 
    * @Title: getQrcodeUrl 
    * @Description: 获取二维码地址 
    * @param @param ticketStr
    * @param @return    设定文件 
    * @return String    返回类型 
    * @throws
     */
    @SuppressWarnings("finally")
    public String getQrcodeUrl(String ticketStr){
        try {
            ticketStr = java.net.URLEncoder.encode(ticketStr,   "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("getQrcodeUrl error:" +  e.getMessage());
        } finally{
            return GET_QRCODE_URL+ticketStr;
        }
        
    }
    
}

